package org.gary.admin.action;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import static lengreen.util.StringUtils.*;
import static lengreen.util.constant.Constant.DateFomaterString.YYYY_MM_DD_HH_MM_SS;
import static org.gary.core.util.Utils.*;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.gary.admin.model.Administrator;
import org.gary.admin.service.AdministratorService;
import org.gary.core.util.ResultMessage;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;

/**
 * admin的Action
 * @author lengreen
 * 
 */
@Component
@Scope("prototype")
public class AdministratorAction extends ActionSupport implements SessionAware,
		ServletResponseAware {
	private static final long serialVersionUID = -5494035530064089100L;

	private Map<String, Object> session;
	private HttpServletResponse response;
	/**记录当前登录系统的管理员 */
	private Administrator loginAdmin;
	private AdministratorService administratorService;
	private Administrator admin;
	/**确认密码*/
	private String password;
	/**管理员列表*/
	private List<Administrator> adminList;
	/**管理员登录时从页面上传来的json登录信息*/
	private String adminJsonString;

	/** 记录当前页 */
	private int start;
	/** 记录分页最大记录条数 */
	private int limit;
	/**选择删除方式*/
	private String mode;
	/**是否可见*/
	private String visible;
	/**返回结果*/
	private String result;

	/**
	 * 添加一个管理员
	 * @throws Exception
	 */
	public void add() throws Exception {
		if (isEquals(password, admin.getPassword())) {
			administratorService.save(admin);
			result = "{'success':'true'}";
		} else {
			result = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
	}

	/**
	 * 登录
	 * @throws Exception
	 */
	public void login() throws Exception {
		JSONObject adminJsonObject = JSONObject.fromObject(adminJsonString);
		Administrator admin = (Administrator) JSONObject.toBean(
				adminJsonObject, Administrator.class);
		result = administratorService.login(admin.getUsername(), admin
				.getPassword());
		if (ResultMessage.admin.LOGIN_SUCCESS.equals(result)) {
			loginAdmin = administratorService.loadByUsername(admin
					.getUsername());
			session.put("admin", loginAdmin);
			if ("administrator".equals(loginAdmin.getUsername())) {
				session.put("s", "true");//判断当前登录系统的administrator是不是超级用户
			} else {
				session.put("s", "false");
			}
			response.getWriter().write("{'result':'success'}");
		} else {
			response.getWriter().write("{'result':'fail'}");
		}
	}

	/**
	 * 退出
	 * @return
	 */
	public String logout() {
		session.clear();
		return SUCCESS;
	}

	/**
	 * 管理员列表
	 * @throws Exception
	 */
	public void list() throws Exception {
		start = parseIndex(start, limit);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put(" entity.visible = ", new Boolean(visible));
		setAdminList(administratorService.list(Administrator.class, start,
				limit, where, new Object[] { " entity.id desc " }));

		JSONObject adminJsonObject = new JSONObject();
		adminJsonObject.put("adminTotal", administratorService
				.selectTotalCount(Administrator.class));

		loginAdmin = (Administrator) session.get("admin");
		JSONArray temp = JSONArray.fromObject(adminList,
				makeDateFormateJsonConfig(YYYY_MM_DD_HH_MM_SS));//json 格式化时间类型
		JSONArray adminListJsonArray = new JSONArray();
		if (!"administrator".equals(loginAdmin.getUsername())) {
			for (Object obj : temp) {
				JSONObject j = JSONObject.fromObject(obj);
				if (!"".equals(j.get("password"))) {
					j.remove("password");
					adminListJsonArray.add(j);
				}
				adminJsonObject.put("adminList", adminListJsonArray);
			}
		} else {
			adminJsonObject.put("adminList", temp);
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(adminJsonObject.toString());
	}

	/**
	 * 更新一个管理员
	 * @throws IOException
	 */
	public void update() throws IOException {
		if (admin != null) {
			Administrator a = administratorService.load(Administrator.class, admin.getId());
			a.setPassword(admin.getPassword());
			administratorService.update(a);
			result = "{'success':'true'}";
		} else {
			result = "{'success':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
	}
	
	/**
	 * 删除管理员，更具mode选择删除模式
	 */
	public void delete() {
		try {
			Administrator a = administratorService.load(Administrator.class, admin.getId());
			if ("delete".equals(getMode())) {
				if(!"administrator".equals(a.getUsername())) {
					administratorService.delete(a);
				}
				result = "{'result':'delete'}";
			} else if ("update".equals(getMode())) {
				if(!"administrator".equals(a.getUsername())) {
					administratorService.update(Administrator.class,
							new Object[] { admin.getId() }, false);
				}
				result = "{'result':'update'}";
			} else {
				result = "{'result':'none'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 检查当前添加的administrator username是否存在
	 * @throws Exception
	 */
	public void checkExist() throws Exception {
		admin.setUsername(URLDecoder.decode(admin.getUsername(), "UTF-8"));
		if(administratorService.checkUsernameExist(admin.getUsername())) {
			result = "{'result':'true'}";
		} else {
			result = "{'result':'false'}";
		}
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(result);
	}
	
	/**
	 * 
	 * @throws IOException
	 */
	public void recover() throws IOException {
		try {
			String result = "";
			if (admin != null) {
				administratorService.update(Administrator.class,
						new Object[] { admin.getId() }, true);
				result = "{'success':'true'}";
			} else {
				result = "{'success':'false'}";
			}
			response.setCharacterEncoding("utf-8");
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Resource
	public void setAdministratorService(
			AdministratorService administratorService) {
		this.administratorService = administratorService;
	}

	public AdministratorService getAdministratorService() {
		return administratorService;
	}

	public void setAdmin(Administrator admin) {
		this.admin = admin;
	}

	public Administrator getAdmin() {
		return admin;
	}

	public void setAdminJsonString(String adminJsonString) {
		this.adminJsonString = adminJsonString;
	}

	public String getAdminJsonString() {
		return adminJsonString;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setAdminList(List<Administrator> adminList) {
		this.adminList = adminList;
	}

	public List<Administrator> getAdminList() {
		return adminList;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getStart() {
		return start;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getLimit() {
		return limit;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getMode() {
		return mode;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	public void setVisible(String visible) {
		this.visible = visible;
	}

	public String getVisible() {
		return visible;
	}
}
